package org.example.springboot.common.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.entity.FmcStatus;
import org.example.springboot.service.FmcBeaconService;
import org.example.springboot.service.FmcControlService;
import org.example.springboot.service.FmcStatusService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 默认回调
 */
@Slf4j
@Component("default")
public class DefaultMqttCallBack extends AbsMqttCallBack {

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private FmcBeaconService fmcBeaconService;

    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * @param topic   主题
     * @param message 消息内容
     */
    @Override
    protected synchronized void handleReceiveMessage(String topic, String message) {
        // 自定义消息处理业务
        if ("FMC_status".equals(topic)) {
            log.info("接收到主题---{}", topic);
            log.info("接收到消息---{}", message);
            // 将耗时任务提交到线程池处理
            executorService.submit(() -> {
                try {
                    fmcControlService.upStatusData(message);
                } catch (Exception e) {
                    log.error("消息处理失败", e);
                }
            });
        }

        if ("FMC_beacon".equals(topic)) {
            // 将耗时任务提交到线程池处理
            executorService.submit(() -> {
                try {
                    fmcBeaconService.saveBeacon(message);
                } catch (Exception e) {
                    log.error("消息处理失败", e);
                }
            });
        }
    }
}

